import { jwtDecode } from 'jwt-decode'
import type { components } from '@/types/ApiInterface'

export type JwtPayload = components['schemas']['User'] & { exp: number }

/**
 * 解码 JWT token
 */
export const decodeToken = (token: string): JwtPayload | null => {
  try {
    return jwtDecode<JwtPayload>(token)
  } catch (error) {
    console.error('Token解析失败:', error)
    return null
  }
}

/**
 * 检查 token 是否过期
 */
export const isTokenExpired = (token: string): boolean => {
  const decoded = decodeToken(token)
  if (!decoded) return true

  const currentTime = Date.now() / 1000
  return decoded.exp < currentTime
}

/**
 * 获取 token 中的用户信息
 */
export const getTokenInfo = () => {
  const token = uni.getStorageSync('token')
  if (!token) return null

  return decodeToken(token)
}
